#!/bin/bash

# 执行 java -version 命令获取 Java 版本信息
java_version=$(java -version 2>&1 | awk -F '"' '/version/ {print $2}')

# 判断是否成功获取 Java 版本信息
if [ -n "$java_version" ]; then
    # 获取脚本所在的目录
    DIR=$(cd "$(dirname "$0")" && pwd)
    echo "DIR = $DIR"
    # 获取同目录下的所有 jar 文件名
    JAR_NAME=$(ls "$DIR"/*.jar 2>/dev/null | head -n 1)
    echo "JAR_NAME = $JAR_NAME"
    if [ -z "$JAR_NAME" ]; then
        echo "No jar file found in current directory."
        exit 1
    fi

    FILE_NAME=$(basename "$JAR_NAME")
    echo "FILE_NAME = $FILE_NAME"

    if pgrep -f "$JAR_NAME" >/dev/null; then
        echo "$FILE_NAME has started successfully. Do not start it again"
    else
        # 启动 jar 进程
        nohup java -jar -Xms256m -Xmx256m "$JAR_NAME" >/dev/null 2>&1 &

        SLEEP_SECOND=0

        # 等待进程结束
        while [ $SLEEP_SECOND -le 15 ]; do
            sleep 3
            SLEEP_SECOND=$[ $SLEEP_SECOND + 3 ]
            PID=$(ps aux | grep "$FILE_NAME" | grep -v grep | awk '{print $2}')
            if [ -z "$PID" ]; then
              if [ $SLEEP_SECOND -gt 15 ]; then
                  echo "Failed to start $FILE_NAME"
                  exit 1
              fi
            else
              echo "$FILE_NAME (PID $PID) started successfully"
              exit 0
            fi
        done
    fi
else
    echo "Java is not installed or not in PATH"
fi